//加载express框架
const express = require('express');
//实例路由
const router = express.Router();
//导入数据模型
const {
  admin
} = require('../model/db');
//===============API写下面================================================

//小程序 获取用户权限
router.get('/wxGetPower', async (req, res) => {
  const {
    openid
  } = req.query;
  if (openid) {
    const result = await admin.findOne({
      openid
    })
    if (result) {
      res.send({
        role: result.role
      })
    } else {
      res.send({
        role: 'none'
      })
    }
  }
})

//管理后台 登录判断
router.post('/admCkLogin', async (req, res) => {
  try {
    const result = await admin.findOne(req.body)
    if (result) {
      res.send({
        status: 'success',
        info: result
      })
    } else {
      res.send({
        status: 'fail'
      })
    }
  } catch (error) {
    res.send({
      status: 'err'
    })
  }
})

//保存管理员
router.post('/saveAdmin', async (req, res) => {
  const {
    _id
  } = req.body
  if (_id) {
    admin.updateOne({
      _id
    }, req.body).then(result => {
      console.log(res)
      res.send('success')
    }).catch(err => {
      console.log(err)
      res.send('fail')
    })
  } else {
    admin.create(req.body).then(result => {
      res.send('success')
    }).catch(err => {
      console.log(err)
      res.send('fail')
    })
  }
})


//删除管理员
router.get('/delAdmin', async (req, res) => {
  const {
    _id
  } = req.query
  admin.findByIdAndRemove(_id).then(result => {
    res.send('success')
  }).catch(err => {
    res.send('fail')
  })
})


//管理后台 获取所有管理员
router.get('/admGetAdmins', async (req, res) => {
  try {
    const {
      currentPage: page,
      pagesize
    } = req.query
    //获取数据库中的记录总数
    const total = await admin.countDocuments()
    //分页获取管理员
    const result = await admin.find().skip((page - 1) * pagesize).limit(pagesize).sort({
      time: -1
    })
    //console.log(result)
    res.send({
      status: 'success',
      total,
      result
    })
  } catch (error) {
    //console.log(error)
    res.send({
      status: 'fail'
    })
  }
})

//===============API写在上面=============================================
//导出路由 
module.exports = router;